import mx.utils.Delegate;

import org.molamil.acto.mc.McConf;
import org.molamil.acto.mc.mcw.LcMcWrapper;

/**
 * <code>LcMcWrapper</code> with a play-play representation of IN and OUT.
 * When the <code>state</code> is set to IN, the MC plays until there is a <code>stop()</code>.
 * When the <code>state</code> is set to OUT, the MC plays again until the end of the timeline
 * ignoring stops.
 *
 * @author Jorge Hernandez
 */
class org.molamil.acto.mc.mcw.PlayPlay extends LcMcWrapper {
	
	
	// Properties
	
	private var monitor:MovieClip;
	
	private var onEfInDelegate:Function;
	private var onEfOutDelegate:Function;
	
	
	// Constructor
	
	public function PlayPlay() {
		onEfInDelegate = Delegate.create(this, onEfIn);
		onEfOutDelegate = Delegate.create(this, onEfOut);
	}
	
	
	// Functions
	
	private function changeState():Void {
		
		// Check the state.
		if (state == STATE_IN || state == STATE_OUT) {
			
			// Create a monitor mc.
			if (monitor == null)
				monitor = mc.createEmptyMovieClip(McConf.monitorMcBaseName, mc.getNextHighestDepth());
			
			// Create a property to hold the previous _currentframe and assign the onEnterFrame.
			monitor.pf = 0;
			monitor.onEnterFrame = state == STATE_IN ? onEfInDelegate : onEfOutDelegate;
			
			// Play, check that if it's state IN it doesn't come from a leftover.
			if (state == STATE_IN && mc._currentframe == mc._totalframes) {
				mc.gotoAndPlay(1);
			} else {
				mc.play();
			}
			
			
		}
		
		// super.changeState() will dispatch the events.
		super.changeState();
		
	}
	
	private function onEfIn():Void {
		if (monitor.pf == mc._currentframe) {
			monitor.removeMovieClip();
			monitor = null;
			state = STATE_ON;
		} else {
			//XXX: Investigate why we need a play here.
			mc.play();
		}
		monitor.pf = mc._currentframe;
	}
	
	private function onEfOut():Void {
		mc.nextFrame();
		if (monitor.pf == mc._currentframe || mc._currentframe == mc._totalframes) {
			monitor.removeMovieClip();
			monitor = null;
			//XXX: Should we get back to frame 1 here?
			mc.gotoAndStop(1);
			state = STATE_OFF;
		} else {
			monitor.pf = mc._currentframe;
		}
	}
	
	
}